import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gongge/config/Config.dart';
import 'package:gongge/utils/AudioUtils.dart';
import '../config/AppConst.dart';
import '../generated/l10n.dart' as langes;
import '../utils/SpUtils.dart';
import '../wight/My.dart';
import '../wight/Seting.dart';
import '../wight/classics.dart';

import '../sqflite/DBManager.dart';
import '../utils/CommUtils.dart';
import '../wight/Travel.dart';
import '../wight/everyday.dart';

///总行数
const GAME_PAD_MATRIX_H = 9;

///总列数
const GAME_PAD_MATRIX_W = 9;

const badgeList = [
  "assets/badge/1.png",
  "assets/badge/2.png",
  "assets/badge/3.png",
  "assets/badge/4.png",
  "assets/badge/5.png",
  "assets/badge/6.png",
  "assets/badge/7.png",
  "assets/badge/8.png",
  "assets/badge/9.png",
  "assets/badge/10.png",
  "assets/badge/11.png",
  "assets/badge/12.png",
  "assets/badge/13.png",
  "assets/badge/14.png",
  "assets/badge/15.png",
  "assets/badge/16.png",
  "assets/badge/17.png",
  "assets/badge/18.png",
  "assets/badge/19.png",
  "assets/badge/20.png",
  "assets/badge/21.png",
  "assets/badge/22.png",
  "assets/badge/23.png",
  "assets/badge/24.png",
  "assets/badge/25.png",
  "assets/badge/26.png",
  "assets/badge/27.png",
  "assets/badge/28.png",
  "assets/badge/29.png",
  "assets/badge/30.png",
  "assets/badge/31.png",
  "assets/badge/32.png",
  "assets/badge/33.png",
  "assets/badge/34.png",
  "assets/badge/35.png",
  "assets/badge/36.png",
];

const IllustrationList = [
  "assets/illustration/Illustration_1_Background.png",
  "assets/illustration/Illustration_2_Background.png",
  "assets/illustration/Illustration_3_Background.png",
  "assets/illustration/Illustration_4_Background.png",
  "assets/illustration/Illustration_5_Background.png",
  "assets/illustration/Illustration_6_Background.png",
  "assets/illustration/Illustration_7_Background.png",
  "assets/illustration/Illustration_8_Background.png",
  "assets/illustration/Illustration_9_Background.png",
  "assets/illustration/Illustration_10_Background.png",
  "assets/illustration/Illustration_11_Background.png",
  "assets/illustration/Illustration_12_Background.png",
  "assets/illustration/Illustration_13_Background.png",
  "assets/illustration/Illustration_14_Background.png",
  "assets/illustration/Illustration_15_Background.png",
  "assets/illustration/Illustration_16_Background.png",
  "assets/illustration/Illustration_17_Background.png",
  "assets/illustration/Illustration_18_Background.png",
  "assets/illustration/Illustration_19_Background.png",
  "assets/illustration/Illustration_20_Background.png",
  "assets/illustration/Illustration_21_Background.png",
  "assets/illustration/Illustration_22_Background.png",
  "assets/illustration/Illustration_23_Background.png",
  "assets/illustration/Illustration_Surfacing_1.png",
  "assets/illustration/Illustration_Surfacing_2.png",
  "assets/illustration/Illustration_reset.png",
];

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  State<HomePage> createState() => HomePageState();
}

//WidgetsBindingObserver 前后台监听
class HomePageState extends State<HomePage>
    with RouteAware, SingleTickerProviderStateMixin, WidgetsBindingObserver {
  AnimationController? controller;
  @override
  void initState() {
    //2.页面初始化的时候，添加一个状态的监听者
    WidgetsBinding.instance.addObserver(this);

    controller = AnimationController(
        duration: Duration(milliseconds: 200), vsync: this //垂直同步
        );
    // controller?.repeat(reverse: false); //循环  从小变大，再从大到小

//动画开始、结束、向前移动或向后移动时会调用StatusListener
    controller?.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller?.stop();
      }
    });
    controller?.forward();

    DBManager().db;

    AudioUtils.getInstance()?.startOrStopBgm();

    super.initState();
  }

  //一些状态改变监听方法
  //监听程序进入前后台的状态改变的方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    switch (state) {
      //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        //  print("应用进入前台======在游戏中吗${Config.isGame}");
        if (Config.isGame) {
          //在游戏当中的话‘
          bool? isvoice = SpUtils.getInstance()?.getBool2(AppConst.voice);
          if (isvoice!) {
            AudioUtils.getInstance()?.resume();
          }
        } else {
          //在首页
          AudioUtils.getInstance()?.startOrStopBgm();
        }

        break;
      //应用状态处于闲置状态，并且没有用户的输入事件，
      // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
      //当前页面即将退出
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
      // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        // print("应用处于不可见状态 后台======");
        AudioUtils.getInstance()?.stopHomeBGm();
        AudioUtils.getInstance()?.pause();
        break;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void didPushNext() {
    //暂停，类似 android的onpause
    // pause();
  }

  void pauseOrResume() {
    //重新看到，类似 android的onpResume
  }

  @override
  void dispose() {
    //3. 页面销毁时，移出监听者
    WidgetsBinding.instance?.removeObserver(this);
    // 释放动画资源
    //  controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
   double hight=  CommUtils.getHeight(context);
    return Scaffold(
      body: Stack(
        children: [
          Container(
            width: CommUtils.getWidth(context),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/bg.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: getType(),
          ), //

          Image.asset('assets/images/top_leaves.png',
              width: double.infinity,
              height:hight*0.05,
              fit: BoxFit.fill),
        ],
      ),
    );

    //满足消分的总个数
  }

  int onClickPosoton = 1;

  Widget getType() {
           double hight = CommUtils.getHeight(context);
    if (onClickPosoton == 1 || onClickPosoton == 3) {
      //第三个item
      return Column(
        children: [
          //中间的显示的内容
          Expanded(
              child: onClickPosoton == 1
                  ? My(
                      setingWight: getSeting(),
                    )
                  : everyDay(
                      setingWight: getSeting(),
                    )),
          getBottom(),
         Image.asset('assets/images/botton_.png',
              width: double.infinity,height: hight*0.09, fit: BoxFit.fill),
        ],
      );
    } else {
      double size = CommUtils.getWidth(context);

      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [

          Padding(
            padding: EdgeInsets.only(
              left: 0,
              top: hight * 0.05,
              right: size * 0.05,
              bottom: 0),
            child: Container(
                    height:hight * 0.05,
              child: Stack(
                children: [
                  Offstage(
                    //是否显示标题
                    offstage: onClickPosoton == 1 || onClickPosoton == 3,
                    child: Align(
                      alignment: Alignment.center,
                      child: CommUtils.getTextGame(
                          context,
                          20,
                          onClickPosoton == 2
                              ? langes.S.of(context).score_
                              : langes.S.of(context).travel_,
                          textColor,
                          textbgColor),
                    ),
                  ),
                  getSeting(),
                ],
              ),
            ),
          ),

          //中间的显示的内容
          Expanded(child: getMiddle()),
          getBottom(),
          Image.asset('assets/images/botton_.png',
              width: double.infinity,height: hight*0.09, fit: BoxFit.fill),
        ],
      );
    }
  }

//设置按钮
  Widget getSeting() {
    return GestureDetector(
      onTap: () {
        AudioUtils.getInstance()?.play("seting_.mp3");
        showPopupWindow();
      },
      child: Align(
        alignment: Alignment.centerRight,
        child: Image.asset('assets/images/seting.png', fit: BoxFit.cover),
      ),
    );
  }

//底部tab
  Widget getBottom() {
    Size size= MediaQuery.of(context).size;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        bottom1(size),
        bottom2(size),
        bottom3(size),
        bottom4(size),
      ],
    );
  }

// 第二个，第四个
  Widget getMiddle() {
    if (onClickPosoton == 2) {
      return ScaleTransition(
        scale: controller!,
        child: classicsWidget(),
      );
    } else {
      return ScaleTransition(
        scale: controller!,
        child: Travel(),
      );
    }
  }

//经典底部
  Widget bottom1(Size size) {
    if (onClickPosoton == 1) {
      //旋转的是当前
      return Column(
        children: [
          Image.asset('assets/images/my_on.png',
              width: size.height*0.06,
              height: size.height*0.06,
              fit: BoxFit.cover),
          CommUtils.getTextGame(
              context, 15, langes.S.of(context).my_, textColor, textbgColor)
        ],
      );
    } else {
      return GestureDetector(
        onTap: () {
          setState(() {
            //重新归位，点击才有动画效果将动画重置到开始前的状态
            controller?.reset();
            controller?.forward();
            onClickPosoton = 1;
          });
        },
        child: Column(
          children: [
            Image.asset('assets/images/my.png',
               width: size.height*0.06,
              height: size.height*0.06,
                fit: BoxFit.cover),
            CommUtils.getTextGame(context, 15, langes.S.of(context).my_,
                Color(0Xff8F919A), Color(0Xff8F919A))
          ],
        ),
      );
    }
  }

  Widget bottom2(Size size) {
    if (onClickPosoton == 2) {
      //旋转的是当前
      return Column(
        children: [
          Image.asset('assets/images/classic_on.png',
           width: size.height*0.06,
              height: size.height*0.06,
              fit: BoxFit.cover),
          CommUtils.getTextGame(
              context, 15, langes.S.of(context).classic_, textColor, textbgColor)
        ],
      );
    } else {
      return GestureDetector(
        onTap: () {
          setState(() {
            controller?.reset();
            controller?.forward();
            onClickPosoton = 2;
          });
        },
        child: Column(
          children: [
            Image.asset('assets/images/classic.png',
             width: size.height*0.06,
              height: size.height*0.06,
                fit: BoxFit.cover),
            CommUtils.getTextGame(context, 15, langes.S.of(context).classic_,
                Color(0Xff8F919A), Color(0Xff8F919A))
          ],
        ),
      );
    }
  }

  Widget bottom3(Size size) {
    if (onClickPosoton == 3) {
      //旋转的是当前
      return Column(
        children: [
          Image.asset('assets/images/daily_on.png',
           width: size.height*0.06,
              height: size.height*0.06,
              fit: BoxFit.cover),
          CommUtils.getTextGame(
              //langes.S.current.daily 有时候不能改变多语言

              context,
              15,
              langes.S.of(context).daily_,
              textColor,
              textbgColor)
        ],
      );
    } else {
      return GestureDetector(
        onTap: () {
          setState(() {
            onClickPosoton = 3;
          });
        },
        child: Column(
          children: [
            Image.asset('assets/images/daily.png',
                  width: size.height*0.06,
              height: size.height*0.06,
                fit: BoxFit.cover),
            CommUtils.getTextGame(context, 15, langes.S.of(context).daily_,
                Color(0Xff8F919A), Color(0Xff8F919A))
          ],
        ),
      );
    }
  }

  Widget bottom4(Size size) {
    if (onClickPosoton == 4) {
      //旋转的是当前
      return Column(
        children: [
          Image.asset('assets/images/trivel_on.png',
         width: size.height*0.06,
              height: size.height*0.06,
              fit: BoxFit.cover),
          CommUtils.getTextGame(
              context, 15, langes.S.of(context).travel_, textColor, textbgColor)
        ],
      );
    } else {
      return GestureDetector(
        onTap: () {
          setState(() {
            controller?.reset();
            controller?.forward();
            onClickPosoton = 4;
          });
        },
        child: Column(
          children: [
            Image.asset('assets/images/trivel.png',
                width: size.height*0.06,
              height: size.height*0.06,
                fit: BoxFit.cover),
            CommUtils.getTextGame(context, 15, langes.S.of(context).travel_,
                Color(0Xff8F919A), Color(0Xff8F919A))
          ],
        ),
      );
    }
  }

/**
 * 设置 弹窗
 */
  void showPopupWindow() {
    showGeneralDialog(
        context: context,
        pageBuilder: (context, anim1, anim2) {
          return Text("");
        },
        // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
        barrierDismissible: true, //控制 Dialog 是否消失
        barrierLabel: "",
        transitionDuration: Duration(milliseconds: 200),
        transitionBuilder: (context, anim1, anim2, child) {
          return Transform.scale(
            scale: anim1.value,
            child: Dialog(
              backgroundColor: Colors.transparent,
              child: Seting(
                callback: (selectIndex) {
                  AudioUtils.getInstance()?.startOrStopBgm();
                  setState(() {});
                },
              ),
            ),
          );
        });
  }
}
